package com.example.myspringbootstarter.autoconfigure;

import com.example.myspringbootstarter.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(Service.class)                      // 类路径下存在Service时才生效
@EnableConfigurationProperties(ServiceProperties.class) // 使ServiceProperties生效
public class ServiceAutoConfiguration {

    @Autowired
    private ServiceProperties serviceProperties;

    @Bean
    @ConditionalOnMissingBean   // 使这个bean成为单例模式
    @ConditionalOnProperty(
            prefix = "my.service",
            value = "enable",
            havingValue = "true"
    )                           // 当配置文件中my.service.enable的值为true时才生效
    public Service service() {
        return new Service(serviceProperties.getPrefix(), serviceProperties.getSuffix());
    }
}
